<template>
  <div class="app-container">
    <div class="top" style="margin-top: 28px;">
      <el-select v-model="project_id" v-loading="projectsLoading" placeholder="选择项目" filterable clearable>
        <el-option label="我的" value="mine" />
        <el-option label="所有" value="" />
        <el-option
          v-for="(item,index) in projects"
          :key="index"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select v-model="isEnable" placeholder="选择状态" clearable style="display: inline-block">
        <el-option label="所有状态" value="" />
        <el-option label="enable" value="1" />
        <el-option label="disable" value="0" />
      </el-select>
      <el-input
        v-model="kwInput"
        placeholder="输入 网站编码/域名/Paypal/Tag 进行筛选"
        style="max-width: 400px"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" type="success" icon="el-icon-search" :disabled="listLoading" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button type="primary" class="el-icon-plus add-btn" @click="handleAction('create', '添加站点')">添加站点
      </el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="data" border fit highlight-current-row style="width: 100%">

      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" block class="demo-table-expand">
            <el-form-item label="Paypal:">
              <span>{{ scope.row.paypal_api_account }}</span>
            </el-form-item>
            <el-form-item label="目录:">
              <span><el-tag :type="scope.row.c_status | statusFilter">{{ scope.row.c_status }}</el-tag>
                {{ scope.row.c_sync_at | lineFilter }}</span>
            </el-form-item>
            <el-form-item label="属性">
              <span v-if="scope.row.type==='PrestaShop'"><el-tag
                                                           :type="scope.row.o_status | statusFilter"
                                                         >{{ scope.row.o_status }}</el-tag>
                {{ scope.row.o_sync_at | lineFilter }}</span>
              <span v-else>
                <el-button @click="handleOptions(scope.row)">配置options</el-button>
              </span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column align="center" label="域名">
        <template slot-scope="scope">
          <el-input v-show="scope.row.edit" v-model="scope.row.domain" class="edit-input" size="small" />
          <span v-show="!scope.row.edit">{{ scope.row.domain }}</span><br>
          <el-tag v-if="scope.row.tag" type="danger">{{ scope.row.tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="enable" width="80">
        <template slot-scope="scope">
          <el-switch
            v-show="!scope.row.edit"
            v-model="scope.row.isEnable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="confirmEdit(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="信息修改" width="260">
        <template slot-scope="scope">
          <el-input
            v-show="scope.row.edit"
            v-model="scope.row.code"
            placeholder="编码"
            class="edit-input"
            size="small"
          />
          <br>
          <el-tooltip class="item" effect="dark" content="消息更新频率" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.m_frequency"
              placeholder="消息更新频率"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="webservice token" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.token"
              placeholder="token"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="wk模块的用户名" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.ds_username"
              placeholder="ds_user"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="wk模块的密码" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.ds_password"
              placeholder="ds_password"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="价格增长比例,0表示使用原价，否则将启用价格增长算法" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.price_increace"
              placeholder="价格增长"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="最低售价(若低于此价格会自动增加)" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.price_min"
              placeholder="最低价格"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="网站起始单号" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.start_order_number"
              placeholder="起始单号"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="网站币种" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.currency_code"
              placeholder="USD"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="网站TAG" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.tag"
              placeholder="tag"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="上传产品最低价格，低于此价格产品会被直接忽略" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.upload_min_price"
              placeholder="upload_min_price"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="上传产品最高价格，高于此价格产品会被直接忽略" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.upload_max_price"
              placeholder="upload_max_price"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="paypal api 账号" placement="right-end">
            <el-input
              v-show="scope.row.edit"
              v-model="scope.row.paypal_api_account"
              placeholder="paypal api account"
              class="edit-input"
              size="small"
            />
          </el-tooltip>
          <span v-show="!scope.row.edit" @click="websiteinfo(scope.row)">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型">
        <template slot-scope="scope" class="mt-tag">
          <el-select v-model="scope.row.type" placeholder="请选择" @change="handleProjectChange(scope.row)">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <i v-if="scope.row.type==='BigCommerce'" class="el-icon-edit" @click="handleBigCommerceConfig(scope.row)" />
          <i v-else-if="scope.row.type==='Shopify'" class="el-icon-edit" @click="handleShopifyConfig(scope.row)" />
          <i
            v-else-if="scope.row.type==='WooCommerce'"
            class="el-icon-edit"
            @click="handleWooCommerceConfig(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" width="180">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.project_id"
            size="mini"
            placeholder="无"
            @change="handleProjectChange(scope.row)"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button
            v-if="scope.row.type==='supplier'"
            slot="reference"
            size="mini"
            type="success"
            plain
            style="margin-left:20px"
            :disabled="!scope.row.project_id"
            icon="el-icon-eye"
            @click="handleProjectAttrPreview(scope.row.project_id)"
          >查看
          </el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="续费" width="200">
        <template slot-scope="scope">
          <span @click="showRenewDialog(scope.row)">{{ scope.row.renew_at.split(' ')[0] }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="400" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.edit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmEdit(scope.row)"
          >
            确认
          </el-button>
          <el-button
            v-show="scope.row.edit"
            class="cancel-btn"
            size="mini"
            icon="el-icon-refresh"
            type="warning"
            @click="cancelEdit(scope.row)"
          >取消
          </el-button>

          <el-button
            v-show="!scope.row.edit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="scope.row.edit=!scope.row.edit"
          >
            修改
          </el-button>
          <el-button
            v-show="!scope.row.edit"
            size="mini"
            icon="el-icon-google"
            type="primary"
            plain
            @click="handleChangeStartOrderNum(scope.row)"
          >起始单号
          </el-button>
          <el-dropdown
            split-button
            type="success"
            size="mini"
            @click="sync('catalog', scope.row.id)"
          >更新目录
            <el-dropdown-menu slot="dropdown" size="mini">
              <el-dropdown-item @click.native.stop="sync('product', scope.row.id)">更新产品属性</el-dropdown-item>
              <el-dropdown-item @click.native.stop="handleCrawlProduct(scope.row.id)">爬取产品</el-dropdown-item>
              <el-dropdown-item @click.native.stop="handleEnableCountry(scope.row)">勾选所有国家</el-dropdown-item>
              <el-dropdown-item @click.native.stop="handleGoogleAdvConfig(scope.row)">转化代码</el-dropdown-item>
              <el-dropdown-item type="danger" divided @click.native.stop="handleAction('delete', scope.row)">删除网站</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      title="修改域名续费日期"
      :visible.sync="renewDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="renewForm"
        :model="renew_form"
        label-position="left"
        label-width="40px"
        style="margin-left: 8%"
      >
        <el-form-item label="域名" label-width="80px">
          <el-input v-model="renew_form.domain" disabled />
        </el-form-item>

        <el-form-item label="域名商" label-width="80px">
          <el-input v-model="renew_form.domain_isp" type="textarea" :rows="5" />
        </el-form-item>
        <el-form-item label="续费日期" label-width="80px">
          <el-date-picker
            v-model="renew_form.renew_at"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="HandleModifyRenew">确 定</el-button>
        <el-button @click="renewDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        v-if="action === 'create'"
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="40px"
        style="margin-left: 8%"
      >
        <el-form-item label="域名" label-width="80px" prop="domain">
          <el-input v-model="temp.domain" />
        </el-form-item>

        <el-form-item label="类型" label-width="80px">
          <el-select v-model="temp.type" placeholder="请选择">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" label-width="80px">
          <el-select v-model="temp.project_id" placeholder="选择项目">
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="续费提醒" label-width="80px">
          <el-date-picker
            v-model="temp.renew_at"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择续费提醒日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <prestaproduct
      :website_id="website_id"
      :domain="domain"
      :pst-visible="pstVisible"
      @closePstDialog="pstVisible=false"
    />
    <websiteoption
      :website_id="website_id"
      :web-visible="websiteOptionVisual"
      @closeMyDialog="websiteOptionVisual=false"
    />
    <bigcommerceconfig
      :website_id="website_id"
      :values-visible="bigcommerceconfigVisual"
      @closeMyDialog="bigcommerceconfigVisual=false"
    />
    <shopifyconfig
      :website_id="website_id"
      :values-visible="shopifyconfigVisual"
      @closeMyDialog="shopifyconfigVisual=false"
    />
    <googleadvconfig
      :website_id="website_id"
      :values-visible="googleadvconfigVisual"
      @closeMyDialog="googleadvconfigVisual=false"
    />
    <woocommerceconfig
      :website_id="website_id"
      :values-visible="woocommerceconfigVisual"
      @closeMyDialog="woocommerceconfigVisual=false"
    />
  </div>
</template>

<script>
import { Post, Put, Delete, dt, Sync, ShowSyncStatus, AddCrawlWebProduct } from '@/api/erp/elicink/website'
import { Get as GetProjects } from '@/api/erp/elicink/project'
import prestaproduct from '@/views/prestashop/element/prestaproduct'
import { EnableCountries, ChangeStartOrderNumber } from '@/api/prestashop/prestashopapi'
import { Get as GetServerStatus } from '@/api/orders/serverstatus'
import websiteoption from '@/views/prestashop/element/websiteoption'
import Bigcommerceconfig from './element/bigcommerceconfig'
import Shopifyconfig from './element/shopifyceconfig'
import Googleadvconfig from './element/googleadvconfig'
import Woocommerceconfig from './element/woocommerceconfig'

export default {
  name: 'SiteManage',
  components: { Woocommerceconfig, Googleadvconfig, Shopifyconfig, Bigcommerceconfig, prestaproduct, websiteoption },
  filters: {
    lineFilter(v) {
      return v && ('|' + v)
    },
    statusFilter(v) {
      switch (v) {
        case '未同步':
          return 'info'
        case '同步中':
          return 'warning'
        case '已同步':
          return 'success'
        case '网络连接异常':
          return 'danger'
      }
    }
  },
  data() {
    var checkDomain = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('域名不能为空'))
      }
      if (value.indexOf('http') === -1) {
        return callback(new Error('域名必须包含http或者https前缀'))
      }
      let domain = value
      domain = domain.replace('http://', '')
      domain = domain.replace('https://', '')
      if (domain.split('.').length < 3) {
        return callback(new Error('域名不合格,必须包含www或者其他二级域名'))
      }
    }
    return {
      rules: {
        domain: [
          { validator: checkDomain, trigger: 'blur' }
        ]
      },
      project_id: null,
      projectsLoading: false,
      renewDialogVisible: false,
      renew_form: {
        'id': '',
        'renew_at': '',
        'domain_isp': ''
      },
      pickerOptions: [
        {
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date(new Date().toDateString())
            end.setTime(start.getTime())
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '前一周',
          onClick(picker) {
            const end = new Date(new Date().toDateString())
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '前一个月',
          onClick(picker) {
            const end = new Date(new Date().toDateString())
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }],
      googleadvconfigVisual: false,
      shopifyconfigVisual: false,
      bigcommerceconfigVisual: false,
      woocommerceconfigVisual: false,
      websiteOptionVisual: false,
      data: [],
      listLoading: true,
      // 输入
      isEnable: '',
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      dialogInputValue: '',
      dialogInputVsible: false,
      title: '',
      temp: {},
      pstVisible: false,
      website_id: '',
      domain: '',
      projects: [],
      typeOptions: [
        {
          label: 'PrestaShop',
          value: 'PrestaShop'
        },
        {
          label: 'WooCommerce',
          value: 'WooCommerce'
        },
        {
          label: 'BigCommerce',
          value: 'BigCommerce'
        },
        {
          label: 'Shopify',
          value: 'Shopify'
        },
        {
          label: 'Wordpress Blog',
          value: 'Wordpress_Blog'
        },
        {
          label: 'runskyblog',
          value: 'runskyblog'
        }
      ]
    }
  },
  created() {
    GetProjects()
      .then(response => {
        this.projects = response.data.data
      })
    this.getList()
  },
  methods: {
    showRenewDialog(row) {
      this.renew_form.domain = row.domain
      this.renew_form.domain_isp = row.domain_isp
      this.renew_form.id = row.id
      this.renew_form.renew_at = row.renew_at
      this.renewDialogVisible = true
    },
    HandleModifyRenew() {
      this.renew_form.only_project = 1
      Put(this.renew_form.id, this.renew_form).then(response => {
        this.renew_form = {
          'id': '',
          'renew_at': '',
          'domain_isp': ''
        }
        this.renewDialogVisible = false
        this.getList()
        this.notify('更新成功')
      })
    },
    websiteinfo(row) {
      let msg = "<ul style='list-style-type:none'>"
      msg += '<li>上传产品最低价格: ' + row.upload_min_price + '</li>'
      msg += '<li>上传产品最高价格: ' + row.upload_max_price + '</li>'
      msg += '<li>   wk模块用户名: ' + row.ds_username + '</li>'
      msg += '<li>    wk模块密码: ' + row.ds_password + '</li>'
      msg += '<li>webservice token: ' + row.token + '</li>'
      msg += '<li>价格增长: ' + row.price_increace + '</li>'
      msg += '<li>最低售价: ' + row.price_min + '</li>'
      msg += '<li>paypal: ' + row.paypal_api_account + '</li>'
      msg += '</ul>'
      this.$alert(msg, row.domain + '配置信息', {
        dangerouslyUseHTMLString: true
      })
    },
    resetTemp() {
      // 获取一年后的日期作为默认续费提醒时间
      const nextYear = new Date()
      nextYear.setFullYear(nextYear.getFullYear() + 1)
      const renewDate = nextYear.toISOString().split('T')[0] // 格式化为 yyyy-MM-dd

      this.temp = {
        domain: 'https://',
        type: 'PrestaShop',
        project_id: this.projects[0]?.id || null,
        renew_at: renewDate
      }
    },
    handleChangeStartOrderNum(row) {
      this.$prompt('请输入起始单号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        ChangeStartOrderNumber({ 'website_id': row.id, 'start_order_number': value })
        this.$message({
          type: 'success',
          message: '你的其实单号是: ' + value + ' 修改成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleGoogleAdvConfig(row) {
      this.website_id = row.id
      this.googleadvconfigVisual = true
    },
    handleBigCommerceConfig(row) {
      this.website_id = row.id
      this.bigcommerceconfigVisual = true
    },
    handleShopifyConfig(row) {
      this.website_id = row.id
      this.shopifyconfigVisual = true
    },
    handleWooCommerceConfig(row) {
      this.website_id = row.id
      this.woocommerceconfigVisual = true
    },
    handleOptions(row) {
      this.website_id = row.id
      this.websiteOptionVisual = true
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    // enable counries
    handleEnableCountry(row) {
      this.listLoading = true
      EnableCountries(row.id).then(response => {
        this.listLoading = false
        this.notify('更新成功')
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      dt({
        kw: this.kwInput,
        showall: 1,
        isEnable: this.isEnable,
        pagesize: this.pagesize,
        project_id: this.project_id,
        page: this.page
      })
        .then(response => {
          const items = response.data.data
          this.data = items.map(v => {
            this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
            v.originalDomain = v.domain //  will be used when user click the cancel botton
            v.originalType = v.type
            this.$set(v, 'inputValue', '')
            this.$set(v, 'inputVsible', false)
            return v
          })
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    cancelEdit(row) {
      row.domain = row.originalDomain
      row.type = row.originalType.concat() // 深拷贝
      row.edit = false
      row.inputVsible = false
      this.$message({
        message: '取消',
        type: 'warning'
      })
    },
    showInput(row) {
      row.inputVsible = true
    },
    confirmEdit(row) {
      Put(row.id, {
        domain: row.domain,
        code: row.code,
        type: row.type,
        tag: row.tag,
        price_increace: row.price_increace,
        price_min: row.price_min,
        upload_min_price: row.upload_min_price,
        upload_max_price: row.upload_max_price,
        m_frequency: row.m_frequency,
        ds_username: row.ds_username,
        ds_password: row.ds_password,
        paypal_api_account: row.paypal_api_account,
        start_order_number: row.start_order_number,
        token: row.token,
        isEnable: row.isEnable
      }).then(response => {
        row.edit = false
        row.inputVsible = false
        this.getList()
        this.notify('更新成功')
      })
    },
    handleCrawlProduct(id) {
      this.listLoading = true
      AddCrawlWebProduct(id).then(response => {
        this.notify('添加成功')
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleClose(row, t) {
      row.type.splice(row.type.indexOf(t), 1)
    },
    handleInputConfirm(row) {
      const inputValue = row.inputValue
      if (inputValue && row.type.indexOf(inputValue) === -1) {
        row.type.push(inputValue)
      }
      row.inputValue = ''
      row.inputVsible = false
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.dialogVisible = true
          this.title = row
          this.resetTemp()
          break
        case 'delete':
          // 先检查服务器关联
          this.checkServerAssociation(row)
          break
        case 'getinfo':
          this.website_id = row.id
          this.domain = row.domain
          this.pstVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          // 确保只发送需要的字段
          const createData = {
            domain: _data.domain,
            type: _data.type,
            project_id: _data.project_id,
            renew_at: _data.renew_at
          }
          Post(createData).then(response => {
            this.dialogVisible = false
            this.dialogInputValue = ''
            this.dialogInputVsible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.dialogInputValue = ''
            this.dialogInputVsible = false
            this.getList()
            this.notify('删除成功')
          })
          return
      }
    },
    showDialogInput() {
      this.dialogInputVsible = true
    },
    handleDialogClose(t) {
      this.temp.type.splice(this.temp.type.indexOf(t), 1)
    },
    // handleDialogInputConfirm() {
    //   const inputValue = this.dialogInputValue;
    //   if (inputValue && this.temp.type.indexOf(inputValue) === -1) {
    //     this.temp.type.push(inputValue);
    //   }
    //   this.dialogInputValue = '';
    //   this.dialogInputVsible = false;
    // },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    async checkServerAssociation(row) {
      // 检查网站是否在服务器配置中
      this.listLoading = true
      try {
        // 获取所有服务器配置
        const response = await GetServerStatus()
        const servers = response.data.data || []

        // 查找包含该网站的服务器
        const associatedServers = []
        servers.forEach(server => {
          if (server.websites && Array.isArray(server.websites)) {
            const hasWebsite = server.websites.some(website =>
              website.id === row.id || website.domain === row.domain
            )
            if (hasWebsite) {
              associatedServers.push({
                ip: server.gsapi_ip,
                isp: server.isp,
                note: server.note
              })
            }
          }
        })

        this.listLoading = false

        if (associatedServers.length > 0) {
          // 如果有服务器关联，显示警告
          const serverList = associatedServers.map(s =>
            `<li>服务器IP: ${s.ip} (${s.isp || '未知'}) ${s.note ? '- ' + s.note : ''}</li>`
          ).join('')

          this.$confirm(
            `<div>
              <p style="color: #E6A23C; font-weight: bold;">⚠️ 警告：该网站已关联到以下服务器：</p>
              <ul style="list-style-type: none; padding-left: 20px;">
                ${serverList}
              </ul>
              <p style="color: #F56C6C; margin-top: 10px;">删除网站前，请先到"服务器"管理页面解除关联关系！</p>
              <p style="margin-top: 10px;">是否仍要继续删除？</p>
            </div>`,
            '网站关联检查',
            {
              confirmButtonText: '继续删除',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: true,
              distinguishCancelAndClose: true,
              confirmButtonClass: 'el-button--danger'
            }
          ).then(() => {
            // 用户确认删除
            this.dialogVisible = true
            this.title = `确认要删除 ${row.domain} 吗？`
            this.temp = row
          }).catch(() => {
            // 用户取消删除
            this.$message({
              type: 'info',
              message: '已取消删除操作'
            })
          })
        } else {
          // 没有服务器关联，直接显示删除确认
          this.dialogVisible = true
          this.title = `确认要删除 ${row.domain} 吗？`
          this.temp = row
        }
      } catch (error) {
        this.listLoading = false
        console.error('检查服务器关联失败:', error)
        // 出错时仍允许删除，但给出提示
        this.$confirm(
          '无法检查服务器关联状态，是否继续删除？',
          '提示',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.dialogVisible = true
          this.title = `确认要删除 ${row.domain} 吗？`
          this.temp = row
        })
      }
    },
    sync(mode, id) {
      this.listLoading = true
      Sync(mode, id).then(response => {
        this.listLoading = false
        this.notify('同步中，请等待后台程序的执行.')
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    show_sync_status(id) {
      ShowSyncStatus(id)
        .then(response => {
          this.$alert(response.msg, '同步信息.', {
            confirmButtonText: '确定'
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleProjectChange(v) {
      this.listLoading = true
      Put(v.id,
        {
          project_id: v.project_id,
          type: v.type,
          only_project: 1
        })
        .then(response => {
          this.listLoading = false
          this.getList()
        }).catch(e => {
          this.listLoading = false
        })
    } // method end
  }
}
</script>

<style scoped>

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 130px
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> span.el-tag--info {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
}
</style>
